package dao;


import model.Chair;
import org.hibernate.Session;
import util.HibernateUtil;

import java.util.ArrayList;
import java.util.List;

public class ChairDaoImpl implements ChairDao {
    Session session;
    public void createChair(Chair chair) {
        try{
            session = HibernateUtil.getSession().openSession();
            session.beginTransaction();
            session.save(chair);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
    }

    public Chair readChair(int index) {
        Chair chair = null;
        try{
            session = HibernateUtil.getSession().openSession();
            chair = (Chair) session.load(Chair.class,index);

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
        return chair;
    }

    public void updateChair(Chair chair) {
        try{
            session = HibernateUtil.getSession().openSession();
            session.beginTransaction();
            session.update(chair);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
    }

    public void deleteChair(Chair chair) {

        try{
            session = HibernateUtil.getSession().openSession();
            session.beginTransaction();
            session.delete(chair);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
    }

    public List<Chair> getAllChairs() {
        Session session = null;
        List<Chair> chairs = new ArrayList<Chair>();
        try {
            session = HibernateUtil.getSession().openSession();
            chairs = session.createCriteria(Chair.class).list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return chairs;
    }
}
